//
//  ImageViewController.m
//  BVSearch
//
//  Created by Allen Thomas on 10/4/10.
//

#import "ImageViewController.h"
#import "HttpConnectionHandler.h"
#import "BVCMSAppDelegate.h"

@implementation ImageViewController

@synthesize imageView;
@synthesize peopleid;
@synthesize imageLoad;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	[imageLoad startAnimating];
	
	BVCMSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
		
	NSLog(@"building query string");
	NSString *urlString = [NSString stringWithFormat:@"https://%@/iphone/FetchImage/%@", delegate.cmsServer, self.peopleid ];
	
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSLog(@"%@", urlString);
	NSURL *url = [NSURL URLWithString:urlString];
	
	HttpConnectionHandler *connectionHandler = [HttpConnectionHandler withURL:url andUsername:delegate.username andPassword:delegate.password];
	
	connectionHandler.errorCallback = @selector(imageDownload_error_callback:);
	connectionHandler.callback = @selector(imageDownload_callback:);
	connectionHandler.delegate = self;
	[connectionHandler processRequest];
	
	
    [super viewDidLoad];
}

/* 
 Selector called by successful image download.
 */
-(void) imageDownload_callback:(NSData *)data {
	[imageLoad stopAnimating];

	UIImage* image = [[UIImage alloc] initWithData:data];
    [imageView setImage:image];
    [image release];
}

/*
 Selector called by unsuccessful image download.
 */
-(void) imageDownload_error_callback:(NSError *)error {
	NSLog(@"Connection failed! Error - %@",
          [error localizedDescription]);
	
	[imageLoad stopAnimating];
	
	UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[connectionError show];
	[connectionError release];
	
}

/*
 Release allocated memory.
 */
- (void)dealloc {
	[imageView release];
	[peopleid release];
	[imageLoad release];
    [super dealloc];
}


@end
